package Demo1_18;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User：Lenovo
 * Date:2025-01-18
 * Time:22:06
 */
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int val) {
        this.val = val;
    }
}

class BinaryTreePreorderTraversal {
    public static void preorderTraversal(TreeNode root) {
        if (root == null) {
            return;
        }
        // 访问根节点
        System.out.print(root.val + " ");
        // 递归遍历左子树
        preorderTraversal(root.left);
        // 递归遍历右子树
        preorderTraversal(root.right);
    }

        public static void main(String[] args) {
            // 创建一个二叉树
            TreeNode root = new TreeNode(1);
            root.left = new TreeNode(2);
            root.right = new TreeNode(3);
            root.left.left = new TreeNode(4);
            root.left.right = new TreeNode(5);
            root.right.left = new TreeNode(6);
            root.right.right = new TreeNode(7);
            // 调用先序遍历方法
            BinaryTreePreorderTraversal.preorderTraversal(root);
        }
}
